package com.yupi.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.usercenter.common.BaseResponse;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.common.ResultUtils;
import com.yupi.usercenter.exception.BusinessExpection;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.model.domain.request.UserDeleteRequest;
import com.yupi.usercenter.model.domain.request.UserLoginRequest;
import com.yupi.usercenter.model.domain.request.UserRegisterRequest;
import com.yupi.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.yupi.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.yupi.usercenter.contant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户接口
 * @author hehe
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;


    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody  UserRegisterRequest userRegisterRequest) throws NoSuchAlgorithmException {
        if(userRegisterRequest == null){
            return null;
        }
        String userPassword = userRegisterRequest.getUserPassword();
        String userAccount = userRegisterRequest.getUserAccount();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String plantCode = userRegisterRequest.getPlantCode();
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,plantCode)){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR);
        }
        Long result =  userService.userRegister(userAccount, userPassword, checkPassword,plantCode);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) throws NoSuchAlgorithmException {
        if(userLoginRequest == null){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"账号或密码不能为空");
        }
        String userPassword = userLoginRequest.getUserPassword();
        String userAccount = userLoginRequest.getUserAccount();
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR,"账号或密码不能为空");
        }
        User result = userService.userLogin(userAccount, userPassword,request);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userObject = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObject;
        if(currentUser == null){
            throw new BusinessExpection(ErrorCode.NULL_ERROR);
        }
        long userid = currentUser.getId();
        //todo 校验用户是否合法

        //向数据库中查询数据
        User user = userService.getById(userid);

        //用户脱敏进行返回
        User userResult = userService.getSafetyUser(user);
        return ResultUtils.success(userResult);
    }


    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username,HttpServletRequest request){
        if(!isAdmin(request)){
            throw new BusinessExpection(ErrorCode.NO_AUTH,"无管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        List<User> userList = userService.list(queryWrapper);

        //将返回的所用用户数据进行脱敏
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody UserDeleteRequest userDeleteRequest,HttpServletRequest request){
        if(!isAdmin(request)){
            throw new BusinessExpection(ErrorCode.NO_AUTH);
        }
        if(userDeleteRequest == null){
            throw new BusinessExpection(ErrorCode.PARAMS_ERROR);
        }
        long id = userDeleteRequest.getId();
        if(id <= 0){ //校验id
            throw new BusinessExpection(ErrorCode.NULL_ERROR);
        }
        boolean result = userService.deleteUser(id);
        return ResultUtils.success(result);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        Integer result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 判断是否为管理员
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request){
        Object userObject = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObject;
        //1.仅管理员可查询
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }
}
